from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

from flask import Flask,render_template,request, make_response


import os
from dal.orm import *
@app.route('/sign')
def sign():
    base_dir = os.path.dirname(__file__)
    print(base_dir) #d:\1MyFiles\code\python\spider\flask1
    count1=5
    orm1=OrmSignRecord()
    count1=orm1.get_count()
    return render_template('sign.html',count1=count1,movies = [''])


@app.route('/sign_data' , methods=['POST'])
def sign_data():
    data = json.loads(request.get_data(as_text=True)) 
    #dict_to_object,以方便访问属性
    data=dict_to_object(data)
    name=data.name
    orm1=OrmSignRecord()
    user1=orm1.get_byName(name)
    if(user1!=null):  #括号可写、可不写。做重复判断
        return Exception("重复")
        #如果已retrun就不会执行到下面，可以在短路径的分支 提前return，使代码更精简，否则会有很多层的if-else缩进。
    user1=SignRecord() #新建一个对象
    user1.name=name
    orm1.add_one(user1)
    return {'result':'ok'}

class Dict(dict):
    # # self.属性写入 等价于调用dict.__setitem__
    __setattr__ = dict.__setitem__
    # # self.属性读取 等价于调用dict.__setitem__
    __getattribute__ = dict.__getitem__
 
    # # 等价于__setattr__ = dict.__setitem__
    # def __setattr__(self, key, value):
    #     dict.__setitem__(self, key, value)
    # 
    # # 等价于__getattribute__ = dict.__getitem__ 或 __getattr__ = dict.__getitem__
    # def __getattribute__(self, item):
    #     return dict.__getitem__(self, item)

# 递归把dict转换成obj对象【兼容obj.属性和obj[属性]】
def dict_to_object(dictObj):
    if not isinstance(dictObj, dict):
        return dictObj
    inst = Dict()
    for k, v in dictObj.items():
        inst[k] = dict_to_object(v)
    return inst

# ————————————————
# 版权声明：本文为CSDN博主「比特币爱好者007」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
# 原文链接：https://blog.csdn.net/weixin_43343144/article/details/92764884


import pandas as pd
from pandas.core.frame import DataFrame

@app.route('/sign_table')
def sign_table():
    count1=5
    orm1=OrmSignRecord()
    allData=orm1.get_all()
    
    #sql查询结果转dataFrame
    cols = [c.name for c in SignRecord.__table__.columns]
    pk = [c.name for c in SignRecord.__table__.primary_key]
    tuplefied_list = [(getattr(item, col) for col in cols) for item in allData]
    df = pd.DataFrame.from_records(tuplefied_list, index=pk, columns=cols)
    print(df)

    return render_template('list.html',count1=count1,users=allData )


@app.route('/table')
def table():
    df=pd.read_excel(r"class02\成绩表.xlsx",'Sheet1')   
    html=df.to_html()
    return html

# pip install pyecharts
from jinja2 import Markup
from pyecharts import options as opts
from pyecharts.charts import Bar
# app = Flask(__name__, static_folder="templates")
def bar_base() -> Bar:
  c = (
    Bar()
      .add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
      .add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
      .add_yaxis("商家B", [15, 25, 16, 55, 48, 8])
      .set_global_opts(title_opts=opts.TitleOpts(title="Bar-基本示例", subtitle="AB数据对比"))
  )
  return c
@app.route("/bar")
def bar():
  c = bar_base()
  return Markup(c.render_embed())
# ————————————————
# 版权声明：本文为CSDN博主「Andy_shenzl」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
# 原文链接：https://blog.csdn.net/Andy_shenzl/article/details/104606336


@app.route('/coll')
def coll():
    count1=5
    orm1=OrmCollRecord()
    departs=orm1.get_departs()
    strs=[]
    for i in departs:
        strs.append(i.depart)
    return render_template('coll.html',count1=count1,users = strs)

@app.route('/coll_get' , methods=['POST'])
def coll_get():
    data = json.loads(request.get_data(as_text=True)) 
    #dict_to_object,以方便访问属性
    data=dict_to_object(data)
    code=data.code
    orm1=OrmCollRecord()
    user1=orm1.get_byCode(code)
    if user1==null:
        user1={}
    else:
        user1=user1.to_json()
    return user1

@app.route('/coll_save' , methods=['POST'])
def coll_save():
    data = json.loads(request.get_data(as_text=True)) 
    #dict_to_object,以方便访问属性
    data=dict_to_object(data)
    orm1=OrmCollRecord()
    orm1.update_one(data)
    return {'result':'ok'}


 


if __name__ == '__main__':
    # app.run()#默认仅本机访问，5000端口
    app.run(host='0.0.0.0',port=5000)#允许所有人访问